package com.zenithmind.task.controller;

import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.common.result.ResultCode;
import com.zenithmind.task.pojo.entity.TaskTag;
import com.zenithmind.task.pojo.query.TaskTagQuery;
import com.zenithmind.task.pojo.vo.TaskTagVO;
import com.zenithmind.task.service.TaskTagService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 任务标签管理控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/zenithMind/task-tag")
@RequiredArgsConstructor
@Tag(name = "任务标签管理", description = "任务标签的创建、查询、更新、删除等功能")
public class TaskTagController {

    private final TaskTagService taskTagService;

    // ==================== 基础CRUD操作 ====================

    @GetMapping("/page")
    @Operation(summary = "分页查询任务标签列表", description = "支持多条件筛选的任务标签分页查询")
    public Result<PageResult<TaskTagVO>> getTaskTagPage(TaskTagQuery query) {
        String userId = UserContext.requireUserId();
        PageResult<TaskTagVO> result = taskTagService.getTaskTagPage(query, userId);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询任务标签详情", description = "根据ID查询任务标签的详细信息")
    public Result<TaskTagVO> getTaskTagById(@Parameter(description = "标签ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        TaskTagVO taskTag = taskTagService.getTaskTagById(id, userId);
        return Result.success(taskTag);
    }

    @PostMapping
    @Operation(summary = "创建任务标签", description = "创建新的任务标签")
    public Result<Boolean> createTaskTag(@Valid @RequestBody TaskTag taskTag) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTagService.createTaskTag(taskTag, userId);
        return Result.success(result);
    }

    @PutMapping
    @Operation(summary = "更新任务标签", description = "更新任务标签信息")
    public Result<Boolean> updateTaskTag(@Valid @RequestBody TaskTag taskTag) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTagService.updateTaskTag(taskTag, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除任务标签", description = "删除指定的任务标签")
    public Result<Boolean> deleteTaskTag(@Parameter(description = "标签ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTagService.deleteTaskTag(id, userId);
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除任务标签", description = "批量删除多个任务标签")
    public Result<Boolean> batchDeleteTaskTags(@RequestBody List<String> ids) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTagService.batchDeleteTaskTags(ids, userId);
        return Result.success(result);
    }

    // ==================== 标签查询方法 ====================

    @GetMapping("/all")
    @Operation(summary = "查询所有可用标签", description = "查询系统中所有可用的任务标签")
    public Result<List<TaskTagVO>> getAllAvailableTags() {
        String userId = UserContext.requireUserId();
        List<TaskTagVO> result = taskTagService.getAllAvailableTags(userId);
        return Result.success(result);
    }

    @GetMapping("/name/{tagName}")
    @Operation(summary = "根据名称查询标签", description = "根据标签名称查询标签信息")
    public Result<TaskTagVO> getTaskTagByName(@Parameter(description = "标签名称") @PathVariable String tagName) {
        String userId = UserContext.requireUserId();
        TaskTagVO result = taskTagService.getTaskTagByName(tagName, userId);
        return Result.success(result);
    }

    @GetMapping("/popular")
    @Operation(summary = "查询热门标签", description = "查询使用频率最高的标签")
    public Result<List<TaskTagVO>> getPopularTags(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = UserContext.requireUserId();
        List<TaskTagVO> result = taskTagService.getPopularTags(limit, userId);
        return Result.success(result);
    }

    @GetMapping("/my")
    @Operation(summary = "查询我创建的标签", description = "查询当前用户创建的所有标签")
    public Result<List<TaskTagVO>> getMyCreatedTags() {
        String userId = UserContext.requireUserId();
        List<TaskTagVO> result = taskTagService.getUserCreatedTags(userId);
        return Result.success(result);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索标签", description = "根据关键词搜索标签")
    public Result<List<TaskTagVO>> searchTags(
            @Parameter(description = "搜索关键词") @RequestParam String keyword) {
        String userId = UserContext.requireUserId();
        List<TaskTagVO> result = taskTagService.searchTags(keyword, userId);
        return Result.success(result);
    }

    // ==================== 标签管理操作 ====================

    @PostMapping("/merge")
    @Operation(summary = "合并标签", description = "将源标签合并到目标标签")
    public Result<Boolean> mergeTags(
            @Parameter(description = "源标签ID") @RequestParam String sourceTagId,
            @Parameter(description = "目标标签ID") @RequestParam String targetTagId) {
        String userId = UserContext.requireUserId();
        Boolean result = taskTagService.mergeTags(sourceTagId, targetTagId, userId);
        return Result.success(result);
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取标签统计信息", description = "获取标签的使用统计信息")
    public Result<Object> getTagStatistics() {
        String userId = UserContext.requireUserId();
        
        List<TaskTagVO> allTags = taskTagService.getAllAvailableTags(userId);
        List<TaskTagVO> popularTags = taskTagService.getPopularTags(5, userId);
        List<TaskTagVO> myTags = taskTagService.getUserCreatedTags(userId);
        
        return Result.success(Map.of(
            "totalTags", allTags.size(),
            "popularTags", popularTags,
            "myTagsCount", myTags.size(),
            "myTags", myTags
        ));
    }

    @PostMapping("/quick-create")
    @Operation(summary = "快速创建标签", description = "快速创建一个简单的标签")
    public Result<TaskTagVO> quickCreateTag(
            @Parameter(description = "标签名称") @RequestParam String tagName,
            @Parameter(description = "标签颜色") @RequestParam(required = false) String tagColor,
            @Parameter(description = "标签描述") @RequestParam(required = false) String description) {
        String userId = UserContext.requireUserId();
        
        TaskTag taskTag = new TaskTag();
        taskTag.setName(tagName);
        taskTag.setColor(tagColor);
        taskTag.setDescription(description);
        
        Boolean created = taskTagService.createTaskTag(taskTag, userId);
        if (created) {
            TaskTagVO result = taskTagService.getTaskTagByName(tagName, userId);
            return Result.success(result);
        } else {
            return Result.fail(ResultCode.FAIL.getCode(), "创建标签失败", null);
        }
    }

    @GetMapping("/suggestions")
    @Operation(summary = "获取标签建议", description = "根据输入获取标签建议")
    public Result<List<TaskTagVO>> getTagSuggestions(
            @Parameter(description = "输入关键词") @RequestParam String input,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "5") Integer limit) {
        String userId = UserContext.requireUserId();
        
        List<TaskTagVO> suggestions = taskTagService.searchTags(input, userId);
        
        // 限制返回数量
        if (suggestions.size() > limit) {
            suggestions = suggestions.subList(0, limit);
        }
        
        return Result.success(suggestions);
    }
}
